/*
  Copyright (C) 2025 mio <stigma@disroot.org>

  Permission is hereby granted, free of charge, to any person obtaining
  a copy of this software and associated documentation files (the
  "Software"), to deal in the Software without restriction, including
  without limitation the rights to use, copy, modify, merge, publish,
  distribute, sublicense, and/or sell copies of the Software, and to
  permit persons to whom the Software is furnished to do so, subject to
  the following conditions:

  The above copyright notice and this permission notice shall be
  included in all copies or substantial portions of the Software.

  THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
  EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
  MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND
  NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE
  LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION
  OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION
  WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
*/
#include "tdeio_gemini.h"
#include "tdeio/global.h"

#include <stdio.h>

#include <tqbuffer.h>

#include <kinstance.h>
#include <kmimetype.h>
#include <tdelocale.h>

#define DEBUG

#ifdef DEBUG
#include <iostream>
#define xinfo(...) do { std::cout << __FUNCTION__ << "(): " << __VA_ARGS__ << std::endl; } while (0)
#else
#define xinfo(...)
#endif

extern "C"
{

int TDE_EXPORT kdemain(int argc, char **argv)
{
    TDEInstance instance("tdeio_gemini");

    if (argc != 4) {
        fputs("usage: tdeio_gemini protocol domain-socket1 domain-socket2\n",
              stderr);
        return 1;
    }

    GeminiSlave slave(argv[2], argv[3]);
    slave.dispatchLoop();
    return 0;
}

} // extern "C"

GeminiSlave::GeminiSlave(const TQCString &poolSocket, const TQCString &appSocket)
    : TDEIO::TCPSlaveBase(1965, "gemini", poolSocket, appSocket, true)
{}

void GeminiSlave::get(const KURL &url)
{
    //    initializeSSL();
    xinfo("connecting to " << url.url());
    TQString host = url.host().isEmpty() ? "localhost" : url.host();

    infoMessage(i18n("Connecting to %1…").arg(host));

    setBlockConnection(true);

    if (!connectToHost(host, 1965)) {
        error(TDEIO::ERR_COULD_NOT_CONNECT, i18n("Failed to connect to host '%1:%2'").arg(host).arg(1965));
        closeDescriptor();
        return;
    }

    char res[1024];
    int i, bytes;
    TQBuffer received;
    received.open(IO_WriteOnly);

    infoMessage(i18n("Connection established to %1").arg(host));

    write(url.url(), url.url().length());
    write("\r\n", 2);

    i = read(res, 2);
    if (i != 2) {
        xinfo("res = " << res);
        error(TDEIO::ERR_CONNECTION_BROKEN, i18n("Unable to read reply type %1.").arg(res));
        closeDescriptor();
        return;
    }

    /* TODO: Support these. */

    if (res[0] == '1') {
        error(TDEIO::ERR_UNSUPPORTED_ACTION,
              i18n("Input response types are currently unsupported"));
        closeDescriptor();
        return;
    }

    if (res[0] == '3') {
        error(TDEIO::ERR_UNSUPPORTED_ACTION,
              i18n("Redirection responses are currently unsupported"));
        closeDescriptor();

        // void redirection( const KURL &_url );
        // redirection()
        return;
    }

    if (res[0] == '4') {
        error(TDEIO::ERR_INTERNAL_SERVER,
              i18n("4x Reponse code from server. Temporarily unavailable."));
        return;
    }

    if (res[0] == '5') {
        error(TDEIO::ERR_SERVICE_NOT_AVAILABLE,
              i18n("5x Reponse code from server. Permanent failure."));
        return;
    }

    if (res[0] == '6') {
        error(TDEIO::ERR_UNSUPPORTED_ACTION,
              i18n("Client Certificate response types are currently unsupported."));
        return;
    }

    if (res[0] != '2') {
        error(TDEIO::ERR_UNSUPPORTED_ACTION,
              i18n("Unknown reply type %1%2").arg(res[0], res[1]));
        return;
    }

    // TODO: As with the above "Support these", this is only handling 2x response
    // type.
    read(res, 1); // SP

    i = readLine(res, 1024);

    if (strncmp(res, "text/gemini", strlen("text/gemini")) == 0) {
        mimeType("text/gemini");
    } else {
        error(TDEIO::ERR_UNSUPPORTED_ACTION,
              i18n("Unsupported MimeType %1").arg(res));
        return;
    }

    while ((i = read(res, 1024)) > 0) {
        bytes += i;
        received.writeBlock(res, i);
        processedSize(bytes);
        //  infoMessage(i18n("Received %1 bytes from %2...").arg(bytes).arg(host));

        if (wasKilled())
            break;
    }

    //    KMimeType::Ptr result = KMimeType::findByContent(received.buffer());
    //    mimeType(result->name());
    totalSize(received.size());
    data(received.buffer());

    //    infoMessage(TQString("MimeType = %1").arg(result->name()));

    closeDescriptor();

    finished();
}
